<?php

namespace app\traits;

use app\model\Organization;
use Exception;
use think\Model;
use think\facade\Cache;

trait CreationLimitTrait
{
    /**
     * 获取创建限制 如果创建限制为0则不限制
     * @param string $oid
     * @param string $tableName
     * @return int
     */
    protected static function getCreationLimit(string $oid,string $tableName) : int
    {
        // 使用缓存避免重复查询
        $cacheKey = 'creation_limit_' . $oid . '_' . $tableName;
        $cachedResult = Cache::get($cacheKey);
        if ($cachedResult !== null) {
            return (int)$cachedResult;
        }

        // 缓存组织等级查询结果
        $gradeCacheKey = 'org_grade_' . $oid;
        $grade = Cache::get($gradeCacheKey);
        if ($grade === null) {
            $grade = Organization::where('id', $oid)->value('grade');
            // 缓存1小时
            Cache::set($gradeCacheKey, $grade, 3600);
        }

        $config = config('organization.capacity');
        $capacity = $config[$grade][$tableName] ?? [];
        $result = array_filter($capacity, function ($value) use ($tableName) {
            return $value['table'] == $tableName;
        });

        if (empty($result)) {
            if (str_contains($tableName, 'category')) {
                $limit = 50;
            } else {
                $limit = 20;
            }
        } else {
            $limit = array_values($result)[0]['limit'] ?? 0;
        }

        // 缓存结果1小时
        Cache::set($cacheKey, $limit, 3600);
        return $limit;
    }

    /**
     * 创建之前检查创建上限
     * @param Model $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeInsert(Model $model): void
    {
        $oid = request()->header('organization');
        if (empty($oid)) {
            throw new Exception('组织ID不能为空，请创建或是加入一个组织');
        }
        $model->oid = $oid;
        $tableName = $model->getTable();
        $limit = self::getCreationLimit($oid, $tableName);
        if ($limit > 0) {
            // 缓存计数查询结果
            $countCacheKey = 'data_count_' . $oid . '_' . $tableName;
            $count = Cache::get($countCacheKey);
            if ($count === null) {
                $count = $model->where('oid', $oid)->count();
                // 计数缓存10分钟
                Cache::set($countCacheKey, $count, 600);
            }

            if ($count >= $limit) {
                throw new Exception('超出创建限制,当前组织等级最多允许创建' . $limit . '条数据');
            }
        }
    }
    /**
     * 创建之后更新计数缓存
     * @param Model $model
     * @return void
     */
    public static function onAfterInsert(Model $model): void
    {
        $oid = $model->oid;
        $tableName = $model->getTable();
        $countCacheKey = 'data_count_' . $oid . '_' . $tableName;
        Cache::inc($countCacheKey);
    }
}